import axios from "@/plugins/axios";
import router from "@/router";
import store from '@/store'
async function getUserInfo() {
    const res = await axios.post('/graphql', {
        query: `{
            getCurrentUser {
              account {
                id
                displayName
                createDate
                isAnonymous
                actived
                 loginCredentials {
                  id
                  domain
                  identifier
                 }
              }
              isSuperAdmin
              isCorporationAdmin
               actor {
                id
                name
                type
              }
            }
          getCurrentEmployee {
            id
            name
            pinyin
            phoneNumber
            officialRank
            isMale
            organization {
              id
              removed
              uniqueCode
              name
              shortName
              parent {
                id
                name
              }
              teams {
                
                getItems {
                  id
                  name
                }
               }
            }
            type
            account {
              id
              displayName
              createDate
              isAnonymous
              actived
              loginCredentials {
                  id
                  domain
                  identifier
                 }
            }
            removed
            toIdentifierString
            jionTeams{
                tags
              }
            }
      
          
        getActorWithCurrentUser {
          id
          name
          type
        }
  }`
    })
    return res.data
}
async function getPermissions(id, accountId) {
    const res = await axios.post('/graphql', {
        query: `{
        authorizationQueryRepository {
          getPermissions(accountId: "${accountId}") {
            id
            action
            description
            resource
            instance
          }
          getRoles(employeeId: "${id}") {
            id
            name
            description
             getPermissions {
              id
              action
              description
            }
          }
        }
      }`
    })
    return res.data
}
// 是否已经获取信息
let allUserInfoStatus = false
const updateUserInfo = async () => {
    let status = true
    const data = await getUserInfo()
    if (data.errors) {
        status = false
    } else if (data.data.getCurrentUser && data.data.getActorWithCurrentUser && data.data.getCurrentEmployee) {
        if (data.data.getCurrentUser.account) {
            if (data.data.getCurrentEmployee) {
                let permissions = []
                let permissionsList = []
                const permissionsRes = await getPermissions(data.data.getCurrentEmployee.id, data.data.getCurrentUser.account.id)
                if (!permissionsRes.data.errors) {
                    permissions = permissionsRes.data.authorizationQueryRepository.getRoles
                    permissions.forEach(item => {
                        item.getPermissions.forEach(aItem => {
                            permissionsList.push(aItem)
                        })
                    })
                    const getPermissions = permissionsRes.data.authorizationQueryRepository.getPermissions
                    permissionsList = [...permissionsList, ...getPermissions]
                }
                store.commit('updateUserInfo', {
                    userInfo: data.data.getCurrentUser.account,
                    employeeInfo: data.data.getCurrentEmployee,
                    loginStatus: true,
                    identity: 'user',
                    permissionsList: permissionsList
                })
                window.sessionStorage.setItem('currentEmployee', JSON.stringify(data.data.getCurrentEmployee));
                status = true
            }
        } else {
            store.commit('updateUserInfo', {
                userInfo: {},
                employeeInfo: {},
                loginStatus: false,
                identity: 'user',
                permissionsList: []
            })
            window.sessionStorage.removeItem('currentEmployee')
            status = false
        }
    } else if (data.data.getCurrentUser.account?.id === '10000') {
        store.commit('updateUserInfo', {
            userInfo: data.data.getCurrentUser.account,
            employeeInfo: {},
            loginStatus: true,
            identity: 'admin',
            permissionsList: []
        })
        status = true
    } else {
        store.commit('updateUserInfo', {
            userInfo: {},
            employeeInfo: {},
            loginStatus: false,
            identity: 'user',
            permissionsList: []
        })
        window.sessionStorage.removeItem('currentEmployee')
        status = false
    }
    allUserInfoStatus = status
    return status
}

router.beforeEach(async (to, from, next) => {
    let res = allUserInfoStatus ? true : await updateUserInfo()
    if (res) {
        next()
    } else {
        next()
    }
})
